define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'bootstrap-datetimepicker'], function($, undefined, Backend, Table, Form) {



    var Controller = {

        index: function() {

            // 初始化表格参数配置

            Table.api.init({

                extend: {

                    index_url: 'document/index/index',

                    add_url: 'document/index/add',

                    edit_url: 'document/index/edit',

                    del_url: 'document/index/del',

                    multi_url: 'document/index/multi',

                    renew_url: 'document/index/renew',

                    sublet_url: 'document/index/sublet',

                    additem_url: 'expenses/index/docitems',

                    table: 'document',

                }

            });



            var table = $("#table");



            // 初始化表格

            table.bootstrapTable({

                url: $.fn.bootstrapTable.defaults.extend.index_url,

                pk: 'id',

                sortName: 'id',
                detailView: true,
                columns: [

                    [

                        { checkbox: true },

                        { field: 'code', title: __('Code') },

                        { field: 'name', title: __('Name') },

                        {

                            field: 'company',

                            title: __('Company'),

                            formatter: function(company) {

                                if (company) {

                                    return company.companyname;

                                }

                                return null;

                            }

                        },

                        {

                            field: 'verify',

                            title: __('VerifyStatus'),

                            formatter: function(value) {

                                var statues = [__('VerifyWait'), __('Verifying'), __('VerifyPass'), __('VerifyRefuse')];

                                return Table.api.formatter.status(statues[value], statues)

                            }

                        },

                        { field: 'start_time', title: __('Start_time'), formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD" },

                        { field: 'end_time', title: __('End_time'), formatter: Table.api.formatter.datetime, datetimeFormat: "YYYY-MM-DD" },

                        // { field: 'create_time', title: __('Create_time'), formatter: Table.api.formatter.datetime },

                        // { field: 'update_time', title: __('Update_time'), formatter: Table.api.formatter.datetime },

                        {

                            field: 'operate',

                            title: __('Operate'),

                            table: table,

                            events: Table.api.events.operate,

                            formatter: function(value, row, index) {
                                if (row.verify > 0 && row.verify < 4) {
                                    this.buttons = [{

                                        name: 'print',

                                        title: '打印合同',

                                        icon: 'fa fa-print',

                                        classname: 'btn btn-success btn-xs btn-print'

                                    }];
                                    return Table.api.buttonlink(this, this.buttons, value, row, index, 'operate');
                                }

                                return Table.api.formatter.operate.call(this, value, row, index);

                            },

                            buttons: [{

                                    name: 'additem',

                                    title: '添加收款项',

                                    icon: 'fa fa-paypal',

                                    classname: 'btn btn-success btn-xs btn-additem'

                                },

                                // {

                                //     name: 'items',

                                //     title: '收款项',

                                //     icon: 'fa fa-cny',

                                //     classname: 'btn btn-success btn-xs btn-item'

                                // },

                                {

                                    name: 'print',

                                    title: '打印合同',

                                    icon: 'fa fa-print',

                                    classname: 'btn btn-success btn-xs btn-print'

                                }
                            ]

                        }

                    ]

                ],
                //注册加载子表的事件。注意下这里的三个参数！
                onExpandRow: function(index, row, $detail) {
                    initSubTable(index, row, $detail);
                }

            });



            // 为表格绑定事件

            Table.api.bindevent(table);



            table.on('click', '.btn-renew', function(e) {

                e.stopPropagation();

                var options = table.bootstrapTable('getOptions');

                var index = $(this).closest('tr').data('index');

                var data = table.bootstrapTable('getData');

                var id = data[index][options.pk]

                Fast.api.open(options.extend.renew_url + (id ? (options.extend.renew_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + id : ''), __('RentRenew'))

            })

            table.on('click', '.btn-sublet', function(e) {

                e.stopPropagation();

                var options = table.bootstrapTable('getOptions');

                var index = $(this).closest('tr').data('index');

                var data = table.bootstrapTable('getData');

                var id = data[index][options.pk]

                Fast.api.open(options.extend.sublet_url + (id ? (options.extend.sublet_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + id : ''), __('RentSublet'))

            })



            table.on('click', '.btn-additem', function(e) {

                e.stopPropagation();

                var options = table.bootstrapTable('getOptions');

                var index = $(this).closest('tr').data('index');

                var data = table.bootstrapTable('getData');

                var id = data[index][options.pk]

                var companyid = data[index]['companyid'];

                Fast.api.open(options.extend.additem_url + (id ? "?docid=" + id + '&cid=' + companyid : ''), '新增合同收费项');

            })



            table.on('click', '.btn-item', function(e) {

                e.stopPropagation();

                var options = table.bootstrapTable('getOptions');

                var index = $(this).closest('tr').data('index');

                var data = table.bootstrapTable('getData');

                var id = data[index][options.pk];



                Backend.api.addtabs('expenses/index/index?addtabs=1&docid=' + id, '合同费用', 'fa fa-cny');



                //  console.log(options.extend);

                //Fast.api.open("expenses/index/add?dialog=1" + (id ? (options.extend.sublet_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + id : ''), __('PayItems'))

            })

            table.on('click', '.btn-print', function(e) {

                e.stopPropagation();

                var options = table.bootstrapTable('getOptions');

                var index = $(this).closest('tr').data('index');

                var data = table.bootstrapTable('getData');

                var id = data[index][options.pk];

                Fast.api.open('document/index/print?id=' + id, '合同打印');


            })

        },

        add: function() {

            $(document).on('changed', function() {
                autoMondiff();
            })

            // Form.api.bindevent($("form[role=form]"), function(data, ret) {
            //     //如果我们需要在提交表单成功后做跳转，可以在此使用location.href="链接";进行跳转
            //     console.log(data);
            //     console.log(ret);
            //     Fast.api.close();
            //     // Fast.api.open('expenses/index/docitems' + (id ? "?docid=" + id + '&cid=' + companyid : ''), '新增合同收费项');
            //     Toastr.success("成功");
            // }, function(data, ret) {
            //     Toastr.success("失败");
            // }, function(success, error) {
            //     //bindevent的第三个参数为提交前的回调
            //     //如果我们需要在表单提交前做一些数据处理，则可以在此方法处理
            //     //注意如果我们需要阻止表单，可以在此使用return false;即可
            //     //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
            //     //Form.api.submit(this, success, error);

            //     return true;
            // });
            //$("input[name='row[type]']").attr('disabled', true)
            Controller.api.bindevent();

        },

        edit: function() {

            Controller.api.bindevent();

        },

        renew: function() {

            Controller.api.bindevent();

        },

        sublet: function() {

            Controller.api.bindevent();

        },
        print: function() {
            $('#flowbnt').on('click', function() {
                submitFlow();
            });
            var submitFlow = function() {
                var docid = $('#docid').val();
                //提交成功后直接提交流程
                var param = { "row[docid]": docid }

                $.post('flow/document/add?ids=46', param, function(json) {
                    if (json.code == 1) {

                        $.post('document/index/updatestate', { 'id': docid, 'verify': 1 }, function(json) {
                            Fast.api.close();
                            window.parent.$("#table").bootstrapTable('refresh');
                        })


                    } else {
                        layer.msg('提交失败');
                    }
                }, 'json')
            }
        },

        docitems: function() {

            Controller.handleCommunityState();

            $("#community_code").change();

            Controller.api.bindevent();

        },

        api: {

            bindevent: function() {

                Form.api.bindevent($("form[role=form]"));

                $("input[name='row[type]']").attr('disabled', true)

            }

        }

    };

    return Controller;

});

//初始化子表格(无线循环)
initSubTable = function(index, row, $detail) {
    var parentid = row.id;
    var cur_table = $detail.html('<table></table>').find('table');

    var html = "";
    html += "<table class='table'>";
    // html += "<thead>";
    // html += "<tr style='height: 40px;'>";
    // html += "<th>项目名称</th>";
    // html += "<th>房产名称</th>";
    // html += "<th>应付金额</th>";
    // html += "<th>已付金额</th>";
    // html += "<th>付款日</th>";
    // html += "</tr>";
    // html += "</thead>";
    $.ajax({
        type: "get",
        url: "expenses/index", //子表请求的地址
        data: { docid: row.id }, //我这里是点击父表后，传递父表列id和nama到后台查询子表数据
        async: false, //很重要，这里要使用同步请求
        success: function(data) {
            html += '<ul class="list-group" >';
            //遍历子表数据
            $.each(data.rows,
                function(n, value) {
                    html += "<tr  align='center'>" +
                        "<td>" + value.project.name + "</td>" +
                        "<td>房产：" + value.house.name + "</td>" +
                        "<td>应付：" + value.amount_total + "</td>" +
                        "<td>已付：" + value.amount_paid + "</td>" +
                        "<td>付款日：" + value.payment_date + "</td>" +
                        "</tr>";
                });
            html += '</table>';
            $detail.html(html); // 关键地方
        }
    });

}


$(function() {

    $('#c-leases').on('click', function() {
        autoMondiff();
    });

});

var autoMondiff = function() {
    var date2 = $('#c-start_time').val();
    var date1 = $('#c-end_time').val();
    // var m = monDiff(date1, date2);
    var m = getDaysBetween(date2, date1);
    console.log(m);
    $('#c-leases').val(m);
}

var monDiff = function(date1, date2) {
    // 拆分年月日
    date1 = date1.split('-');
    // 得到月数
    date1 = parseInt(date1[0]) * 12 + parseInt(date1[1].replace(/\b(0+)/gi, "")) + parseInt(date1[2].replace(/\b(0+)/gi, "")) / 30;
    // 拆分年月日
    date2 = date2.split('-');

    // 得到月数
    date2 = parseInt(date2[0]) * 12 + parseInt(date2[1].replace(/\b(0+)/gi, "")) + parseInt(date2[2].replace(/\b(0+)/gi, "")) / 30;

    var m = Math.round(date1 - date2);
    return m;
}

function getDaysBetween(dateString1, dateString2) {
    var startDate = Date.parse(dateString1);
    var endDate = Date.parse(dateString2);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    // alert(days);
    return days;
}

// var submitData = function(i) {


//     var amount_total_control = $("input[name='amount_total']");

//     var payment_date_control = $("input[name='payment_date']");

//     var amount_unitprice = $("input[name='amount_unitprice']");

//     if (i >= amount_total_control.length) {

//         layer.msg('已完成提交的请求');

//         Fast.api.close();

//         //parent.$("a.btn-refresh").trigger("click");

//         return;

//     }

//     var param = $('form').serializeArray();

//     param.push({ 'name': 'row[amount_total]', 'value': amount_total_control.eq(i).val() });

//     param.push({ 'name': 'row[payment_date]', 'value': payment_date_control.eq(i).val() });

//     param.push({ 'name': 'row[unitprice]', 'value': amount_unitprice.eq(i).val() });

//     $.post('expenses/index/add', param, function(json) {

//         // console.log(json);

//         i++;

//         submitData(i);

//     }, 'json')



// }